#!/bin/bash
# 微服务启动脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 项目根目录
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BUILD_DIR="$PROJECT_ROOT/build"

# 加载环境变量
ENV_FILE="$PROJECT_ROOT/.env"
if [ -f "$ENV_FILE" ]; then
    set -a
    source "$ENV_FILE"
    set +a
fi

if [ -z "$JWT_SECRET" ]; then
    export JWT_SECRET="dev-gateway-secret-placeholder"
    echo -e "${YELLOW}⚠ 未检测到 JWT_SECRET，使用开发环境占位值${NC}"
fi

echo "========================================="
echo "  微服务多进程启动脚本"
echo "========================================="
echo ""

# 检查Redis
echo -n "检查Redis状态... "
if redis-cli ping > /dev/null 2>&1; then
    echo -e "${GREEN}✓ Redis运行中${NC}"
else
    echo -e "${RED}✗ Redis未运行${NC}"
    echo "请先启动Redis: redis-server --daemonize yes"
    exit 1
fi

# 检查可执行文件
echo -n "检查可执行文件... "
if [ ! -f "$BUILD_DIR/services/ping_service/ping_service" ]; then
    echo -e "${RED}✗ ping_service未编译${NC}"
    echo "请先编译: cd build && make ping_service"
    exit 1
fi
echo -e "${GREEN}✓ 可执行文件存在${NC}"

echo ""
echo "========================================="
echo "  启动服务"
echo "========================================="

# 清理旧的PID文件
rm -f /tmp/ping_service_*.pid

# 启动PingService实例1
echo -n "启动 PingService 实例1 (端口9003)... "
$BUILD_DIR/services/ping_service/ping_service 9003 > /tmp/ping_service_9003.log 2>&1 &
PID1=$!
echo $PID1 > /tmp/ping_service_9003.pid
sleep 2

if kill -0 $PID1 2>/dev/null; then
    echo -e "${GREEN}✓ PID=$PID1${NC}"
else
    echo -e "${RED}✗ 启动失败${NC}"
    cat /tmp/ping_service_9003.log
    exit 1
fi

# 启动PingService实例2
echo -n "启动 PingService 实例2 (端口9004)... "
$BUILD_DIR/services/ping_service/ping_service 9004 > /tmp/ping_service_9004.log 2>&1 &
PID2=$!
echo $PID2 > /tmp/ping_service_9004.pid
sleep 2

if kill -0 $PID2 2>/dev/null; then
    echo -e "${GREEN}✓ PID=$PID2${NC}"
else
    echo -e "${RED}✗ 启动失败${NC}"
    cat /tmp/ping_service_9004.log
    exit 1
fi

echo ""
echo "========================================="
echo "  验证服务注册"
echo "========================================="

sleep 1

# 检查服务注册
INSTANCE_COUNT=$(redis-cli HLEN service:PingService:instances)
echo "注册的实例数: $INSTANCE_COUNT"

if [ "$INSTANCE_COUNT" -ge 2 ]; then
    echo -e "${GREEN}✓ 服务注册成功${NC}"
    redis-cli HGETALL service:PingService:instances | grep -E "ping-service-|port"
else
    echo -e "${YELLOW}⚠ 部分实例未注册${NC}"
fi

echo ""
echo "========================================="
echo "✅ 微服务启动完成"
echo "========================================="
echo "运行的服务："
echo "  - PingService:9003 (PID=$PID1)"
echo "  - PingService:9004 (PID=$PID2)"
echo ""
echo "日志文件："
echo "  - /tmp/ping_service_9003.log"
echo "  - /tmp/ping_service_9004.log"
echo ""
echo "停止服务："
echo "  bash $PROJECT_ROOT/scripts/stop_microservices.sh"
echo ""
